﻿#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
using namespace std;
const uint16_t PORT = 1234;
void clear(string buf, string& tem) {	//去除非法字符
	for (int i = 0, j = 0; buf[i] != '\0'; i++)
		if (buf[i] != '\n' && buf[i] != '\r' && buf[i] != ' ')
		{
			tem.insert(j, buf, i, 1);
			j++;
		}
}
void toLower(string& tem) {
	for (int i = 0, j = 0; tem[i] != '\0'; i++) {
		if (tem[i] >= 'A' && tem[i] <= 'Z') {
			tem[i] = tem[i] + 'a' - 'A';
		}
	}
}
void Modify(string buf, string& tem) {
	clear(buf, tem);
	toLower(tem);
}

int clin_sock = 0;
struct sockaddr_in serv_addr;
string buf = "\0", question = "\0";
void my_socket() {
	clin_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (clin_sock < 0) {
		perror("socket");
		exit(1);
	}
	// AF_INET :   表示使用 IPv4 地址		可选参数
	// SOCK_STREAM 表示使用面向连接的数据传输方式，
	// IPPROTO_TCP 表示使用 TCP 协议
}
void my_connect() {
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");		//本地测试
	//serv_addr.sin_addr.s_addr = inet_addr("172.20.17.81");  //异地IP地址
	//hostname -I
	serv_addr.sin_port = htons(PORT);  //端口
	if (connect(clin_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
		perror("connect");
		close(clin_sock);
		exit(1);
	}
}
void my_read() {
	char buffer[32] = {0};
	ssize_t n = read(clin_sock, buffer, 32);
	if (n < 0) {
		perror("read");
		close(clin_sock);
		exit(1);
	}
	buf.assign(buffer,n);
	auto pos = buf.find('\0');
	if(pos!=string::npos){
		buf.erase(pos);
	}
	question = "\0";
}
void my_write() {
	char out[32]={0};
	memcpy(out,question.c_str(),question.size());
	if (write(clin_sock, out, 32) < 0) {
		perror("write");
		close(clin_sock);
		exit(1);
	}
}
void my_close() {
	close(clin_sock);
}
int main() {
	
	while (1) {
		cout << "输入一个单词（输入q关闭应用):\n";	
		question = "\0";
		buf = "\0";
		string tem = "\0";
		cin >> tem;
		Modify(tem, question);
		my_socket();
		my_connect();
		if (question == "q") {
			break;
		}
		else {
			my_write();
			my_read();
			cout << "英汉互译结果：" << buf << endl;
		}
		my_close();
		
	}
	return 0;
}